import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:sudoku/util/RecordModel.dart';

class UserPreferences {
  static UserPreferences? _singleton;
  static SharedPreferences? _prefs;
  static String RECORD = "sp_records";

  static Future<UserPreferences> getInstance() async {
    if (_singleton == null) {
      if (_singleton == null) {
        var singleton = UserPreferences._();
        await singleton._init();
        _singleton = singleton;
      }
    }
    return _singleton!;
  }

  UserPreferences._();

  Future _init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  static List getHistoryRecord() {
    if (_prefs == null) return [];
    String recordStr = _prefs!.getString(RECORD) ?? "[]";
    return json.decode(recordStr);
  }

  static Future addRecord(RecordModel model) {
    if (_prefs == null) return Future(() => null);
    List records = getHistoryRecord();
    records.insert(0, model);
    return _prefs!.setString(RECORD, json.encode(records));
  }



  // static Future delRecord(Map map) {
  //
  // }


}
